package com.wxd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxd.reggie.dto.DishDto;
import com.wxd.reggie.entity.Dish;
import com.wxd.reggie.entity.DishFlavor;
import com.wxd.reggie.mapper.DishMapper;
import com.wxd.reggie.service.DishFlavorService;
import com.wxd.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;


    /**
     * 添加菜品
     *
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveDishOfFlave(DishDto dishDto) {
        log.info("菜品数据{}", dishDto);
        //1. 将菜品数据保存到dish表中
        this.save(dishDto);
        // dish_flavor中要保存dish_id 该功能要手动实现
        Long dishId = dishDto.getId();// 菜品id
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(item -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        //2. 将口味数据保存到dish_flavor表中
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getDishOfFlavorById(long id) {
        DishDto dishDto = new DishDto();
        Dish dish = this.getById(id);
        BeanUtils.copyProperties(dish, dishDto);
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper();
        lqw.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> list = dishFlavorService.list(lqw);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    public boolean updateDish(DishDto dishDto) {
        log.info("要更新的数据---{}", dishDto);
        this.updateById(dishDto);
        // 根据菜品id先将该菜品下所有的口味删除掉
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(lqw);
        // 再重新添加菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(item -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        boolean flag = dishFlavorService.saveBatch(flavors);
        return flag;
    }
}
